
import Vue from 'vue'

import core from 'gapi/core'

import App from './App'

import cache from 'gapi/cache.js'

import clientUi from 'gapi/clientUi.js'

import location from 'gapi/location.js'

import commonPage from 'clientApi/commonPage.js'

import * as util from 'js/util.js'

import widget from 'gapi/widget'

new core('dmsaas').start(() => {

	new Vue({
		el: 'body',
		data:{
            selectId:'',
            positionResult:{},
            addressList:[],
            map:{},
            key:['商场','超市','地铁站','餐馆','学校','公司','酒店','公交站','公园','银行'],
            // key:['商场','超市','公司','酒店','学校','餐馆','景点','休闲娱乐','车主服务','美食','小吃快餐','火锅','中餐','酒吧','咖啡厅','快捷酒店','星级酒店','特价酒店','宾馆','公寓酒店','招待所','青年旅社','公交站','地铁站加油站','停车场','火车票点','汽车站','网吧','洗浴','足疗','KTV','电影院','按摩','银行','意愿','药店','厕所','ATM','快递','花店','照相馆','幼儿园','菜市场','小学','书店','车管所','眼镜店','五金店','蛋糕店','美容美发','公园','名胜古迹','度假村','步行街','其他'],
            position:[
                        // {
                        //     "name":"\u516b\u7ef4\u5b66\u6821\u5317\u95e8",
                        //     "address":'sidfjskdfsjfsl',
                        //     "coordinate":"116.399957,39.91095"
                        // },
                        // {
                        //     "name":"\u516b\u7ef4\u5b66\u6821\u5357\u95e8",
                        //     "address":'sjkdfksjdlkslsad',
                        //     "coordinate":"116.399957,39.91095"
                        // }
                    ],
            tune_distance: 500,
            search_end: false
		},
        components: {
            App
        },
		methods:{
			init(){

                this.tune_distance = util.getUrddataString('tune_distance')
                // alert(this.tune_distance)
                let lat = util.getUrddataString('address_lat')
                let lng = util.getUrddataString('address_lng')
                
                setTimeout(() => {
                    this.map = new BMap.Map("l-map")
                    this.searchAddress(lng,lat)

                    let point = new BMap.Point(lng, lat)

                    let img = util.KqMapImg.attendImgY;
                    let myIcon = new BMap.Icon(img, new BMap.Size(24, 32),{
                        imageSize:new BMap.Size(25,31)
                    })
                    
                    let mk = new BMap.Marker(point,{icon: myIcon});

                    this.map.addOverlay(mk);
                    this.map.panTo(point);
                    this.map.centerAndZoom(new BMap.Point(lng,lat), 15)//FIXME 定位
                },0)
                
			},
			//切换地图
			switchView(address){
				this.positionResult = address
                var point = address.coordinate
				this.map.panTo(new BMap.Point(point.lng,point.lat))

                let img = util.KqMapImg.attendImgY;
                let myIcon = new BMap.Icon(img, new BMap.Size(24, 32),{
                    imageSize:new BMap.Size(25,31)
                })

				let marker = new BMap.Marker(point,{icon: myIcon})
				this.map.clearOverlays();
				this.map.addOverlay(marker)
			},
            //查询附近位置
			searchAddress(x,y){
				var t = this
                var mypoint = new BMap.Point(x, y)
                t.map.centerAndZoom(mypoint, 12)
                var options = {
                    pageCapacity:50,//设置搜索结果条数
                    // renderOptions:{map:t.map},
                    onSearchComplete: function(results){
                        // 判断状态是否正确
                        if (local.getStatus() == BMAP_STATUS_SUCCESS){
                            for (var i = 0;i< results.length; i ++) {
                                // let list = []
                                for (var j = 0; j < results[i].getCurrentNumPois(); j ++){
                                    let s = {}
                                    s.id = ""+i+j
                                    s.name = results[i].getPoi(j).title
                                    s.address = results[i].getPoi(j).address
                                    s.coordinate = results[i].getPoi(j).point
                                    //todo 筛选点经纬度重复的地址
                                    t.addressList.push(s)
                                }
                                // if(list.length){
                                //     t.addressList.push(list)
                                // }
                            }
                            t.search_end = true
                            //快速排序
                            var quickSort=function(arr){   
                                //如果数组长度小于等于1无需判断直接返回即可  
                                if(arr.length<=1){  
                                    return arr;  
                                }  
                                var midIndex = arr.length/2;
                                var midIndexVal=arr.splice(midIndex,1);//取基准点的值,splice(index,1)函数可以返回数组中被删除的那个数arr[index+1]  

                                var left=[];//存放比基准点小的数组  
                                var right=[];//存放比基准点大的数组  
                                //遍历数组，进行判断分配  
                                for(var i=0;i<arr.length;i++){  
                                    var j = parseInt(arr.length/2 - 1);
                                    var point1 = arr[i].coordinate;
                                    var point2 = arr[j].coordinate;
                                    console.log(j,y,x)
                                    var s1 = t.getDistanceBaidu(y,x,point1.lat,point1.lng);
                                    var s2 = t.getDistanceBaidu(y,x,point2.lat,point2.lng);
                                    if (s1 < s2) {
                                        left.push(arr[i]);//比基准点小的放在左边数组 
                                    }
                                    else{  
                                        right.push(arr[i]);//比基准点大的放在右边数组  
                                    }  
                                }  
                                //递归执行以上操作,对左右两个数组进行操作，直到数组长度为<=1；  
                                return quickSort(left).concat(midIndexVal,quickSort(right));  
                            };  
                            t.addressList = quickSort(t.addressList)
                            t.switchView(t.addressList[0]) //设置默认选中地点
                            t.selectId = t.addressList[0].id
                        }
                    }
                }
                var local = new BMap.LocalSearch(t.map, options)
                // alert(this.tune_distance)
                local.searchNearby(t.key,mypoint, t.tune_distance)
			},
            // 确认按钮
            submit(){
                let position = {}
                position.name = this.positionResult.name
                position.address = this.positionResult.address
                position.coordinate = this.positionResult.coordinate.lng+","+this.positionResult.coordinate.lat
                // alert(JSON.stringify(position))
                commonPage.goBack(1,{'key':'position','value':position})
            },
            searchPosition(){
                let locationList = JSON.stringify(this.addressList)
                let encodeStr = encodeURIComponent(`tune_distance=${this.tune_distance}&locationList=${locationList}`)
                window.location.href=`dmsaas://KaoqinPositionSearch?urdData=${encodeStr}` 
            },
            updateDate(data){
                console.log(data)
                if(data&&data !== undefined){
                    let key = data.key
                    let value = data.value
                    if(key == 'kqPositionSearchResult'){
                        // let list = []
                        // this.addressList = []
                        // value.id="searchResult"
                        // list.push(value)
                        // this.addressList.push(value)
                        // this.searchAddress(value.coordinate.lng,value.coordinate.lat)
                        this.addressList = []
                        this.addressList.push(value)
                        this.switchView(value) //设置默认选中地点
                        this.selectId = this.addressList[0].id
                    }
                }
                
            },
            Rad(d){
                return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
            },
            //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
            getDistanceBaidu(lat1,lng1,lat2,lng2){
                var radLat1 = this.Rad(lat1);
                var radLat2 = this.Rad(lat2);
                var a = radLat1 - radLat2;
                var  b = this.Rad(lng1) - this.Rad(lng2);
                var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
                s = s * 6378.137 ;// EARTH_RADIUS;
                s = Math.round(s * 10000) / 10000; //输出为公里
                //s=s.toFixed(4);

                return s;
            }
		},
		ready(){
            this.init()
            window.loadData = this.updateDate

             /**
             * 设置 添加确认按钮
             * @type {String}
             */
            commonPage.updateTitleBar({
                backAction: '',
                leftDisplay: false,
                leftText: '',
                leftAction: '',
                rightDisplay: true,
                rightText: '确认',
                rightAction: 'doSubmit'
            })

            window.doSubmit = this.submit
		}
	})

})